/**
 * @desc : 自定义列表
 * @author : xianggang
 * @date : 2019-08-31 15:10
 */
var app = angular.module('app', ["base", 'baseDirective', 'ui.codemirror']);
app.controller("formCustSqlController", ['$scope', 'baseService', 'formCustSqlService', 'ArrayToolService', function ($scope, baseService, formCustSqlService, ArrayTool) {

	$scope.service = formCustSqlService;
	$scope.ArrayTool = ArrayTool;
	$scope.init = function () {

		// 拿出数据源
		baseService.postForm(__ctx + '/sys/sysDataSource/listJson', {
			page: 1,
			rows: 99
		}).then(function (result) {

			// 所有数据源
			$scope.AllSysDataSources = result.rows;
		});

		// 如果是新增
		var operType = $.getParam("operType");
		$scope.isAdd = operType == "add";
		$scope.isCopy = operType == "copy";
		$scope.isEdit = operType == "edit";
		$scope.isSee = operType == "view";
		if ($scope.isAdd) {
			$scope.data = {
				type: "1",// 1:sql,2:其他,目前只有1
				dsKey: "dataSourceDefault",// 默认本地数据源
				initQuery: "1",// 是否默认查询
				canExport: "1",
				pageSize: "10",
				showRowsNum: "1",
				status: "1",
				sqlContent: "",
				fieldsList: [],
				custForm: {},
				expand: {}
			};
			return;
		}

		// 获取数据
		baseService.postForm(getCtxUrl('/form/formCustSql/get?id={id}', true), {}).then(function (data) {

			if (data.isOk) {
				$scope.data = data.data;

				// 如果是copy,则将id设置为空
				if ($scope.isCopy) {
					$scope.data.id = "";
					$scope.data.name = $scope.data.name + "-复制";
					$scope.data.code = $scope.data.code + "-copy";
				}

				// 设置字段扩展
				for (var i = 0; i < $scope.data.fieldsList.length; i++) {
					$scope.data.fieldsList[i].expand = JsonUtil.ps($scope.data.fieldsList[i].expand) || {};
				}

				// 设置可查询列表
				$scope.search = $scope.search || {};
				$scope.button = $scope.button || {};
				$scope.search.canSelectList = $.extend(true, [], $scope.data.fieldsList);
				$scope.search.selectSearchList = JsonUtil.ps(data.data.conditions);
				$scope.button.buttonList = JsonUtil.ps(data.data.buttons) || [];
				$scope.data.expand = JsonUtil.ps($scope.data.expand) || {};
				$scope.data.custForm ? '' : $scope.data.custForm = {};

				$scope.handleButtonList();

				// 当前查询sql的
				$scope.sqlTableList = JsonUtil.ps(data.data.sqlTableList) || [];

			} else {
				$.Dialog.error(data.msg);
			}
		});

	}

	$scope.handleButtonList = function () {
		// 兼容历史的按钮打开数据设置,以后可以删掉
		for (var i = 0; i < $scope.button.buttonList.length; i++) {
			var clickType = $scope.button.buttonList[i].clickType;
			$scope.button.buttonList[i].expand = JsonUtil.ps($scope.button.buttonList[i].expand) || {};
			var expand = $scope.button.buttonList[i].expand;
			var hrefSetting = expand.hrefSetting || {};
			// 如果有clickType并且没有expand.openType 则表示是历史数据
			if (clickType && !hrefSetting.openType) {
				$scope.button.buttonList[i].expand.hrefSetting = {
					openType: clickType,
					width: "100",
					height: "100",
					widthUnit: "%",
					heightUnit: "%"
				}
				// 删掉clickType
				delete $scope.button.buttonList[i].clickType;
			}
		}
	}


	$scope.$root.$on('afterSaveEvent', function (event, data) {

		if (parent.reload) {
			parent.reload();
		}
		if (data.r) {
			location.reload();
		} else {
			$.Dialog.close(window);
		}
	});

	// 格式化sql
	$scope.formatSql = function (sql) {

		sql = sqlFormatter.format(sql, {
			language: 'sql'
		});
		return sql;
	}

	// 解析并获取字段的备注
	var getFieldDesc = function (field) {

		var fieldDesc = "";

		// 判断是否是数据字典
		if (field.fieldDesc && field.fieldDesc.indexOf("dic") > 0) {
			field.controlType = 5; // 数据字典
			var idx = field.fieldDesc.indexOf("dic");
			field.dateFormat = field.fieldDesc.substring(idx + 4, field.fieldDesc.length).trim();
			field.fieldDesc = field.fieldDesc.substring(0, idx).trim();
			return;
		}

		if (field.fieldDesc && (field.fieldDesc.indexOf(":") > 0 || field.fieldDesc.indexOf("：") > 0 || field.fieldDesc.indexOf("；") > 0 || field.fieldDesc.indexOf("，") > 0 || field.fieldDesc.indexOf(",") > 0 || field.fieldDesc.indexOf(";") > 0)) {

			var match = field.fieldDesc.match(/\d+/ig);
			if (match) {
				var firstNum = match[0];
				var firstNumIndex = field.fieldDesc.indexOf(firstNum);
				if (firstNumIndex >= 2) {
					fieldDesc = field.fieldDesc.substring(0, firstNumIndex);
					if (fieldDesc) {
						fieldDesc = fieldDesc.replaceAll("，", "").replaceAll("：", "");
						if (fieldDesc.endWith(",") || fieldDesc.endWith(".") || fieldDesc.endWith(":")) {
							fieldDesc = fieldDesc.substring(0, fieldDesc.length - 1);
						}
					}
				}
				field.fieldDesc = JsonUtil.getJs(field.fieldDesc);
			}
		}

		if (field.fieldDesc && field.fieldDesc.indexOf("{") >= 0) {
			var temp = field.fieldDesc;
			field.fieldDesc = temp.substring(0, temp.indexOf("{"));
			var dateFormat = temp.substring(temp.indexOf("{"), temp.length);
			if (!field.fieldDesc) {
				field.fieldDesc = temp;
			}
			field.fieldDesc = fieldDesc;
			dateFormat = JsonUtil.ps(dateFormat);
			if (dateFormat) {
				field.controlType = 4; // 下拉框
				field.dateFormat = JSON.stringify(dateFormat);
			}

		} else {
			field.fieldDesc = field.fieldDesc.tuoFeng();
		}

		field.fieldDesc = field.fieldDesc.trim();

		if (!field.dateFormat && field.fieldDesc && (field.fieldDesc.indexOf("是否") >= 0 || field.fieldName.indexOf("is") == 0)) {
			field.controlType = 11;
			field.dateFormat = '{"0":"否","1":"是"}';
		}
	};

	// 解析SQL
	$scope.parseSql = function () {

		if (!$scope.data.dsKey) {
			$.Dialog.error("请选择数据源");
			return;
		}
		if (!$scope.data.sqlContent) {
			$.Dialog.error("请输入sql");
			return;
		}

		// 保存数据
		baseService.post(__ctx + '/form/formCustSql/parseSql', {
			id: $scope.data.id,
			sqlContent: $scope.data.sqlContent,
			dsKey: $scope.data.dsKey
		}).then(function (data) {

			if (data.isOk) {

				data = data.data;
				var sqlFieldList = [];
				var sqlTableList = [];
				var sqlTableJSON = {};
				for (var a = 0; a < data.length; a++) {
					var ctrl = data[a].controlContent;
					getFieldDesc(data[a]);
					if (ctrl) {
						ctrl = util.parseToJson(ctrl);
						data[a].sn = sqlFieldList.length + 1;
						data[a].isSearch = 1;
						sqlFieldList.push(data[a]);
					} else {
						data[a].sn = sqlFieldList.length + 1;
						data[a].isSearch = 1;
						sqlFieldList.push(data[a]);
					}
					if (!sqlTableJSON[data[a].tableName]) {
						sqlTableList.push({
							tableAlias: data[a].tableAlias,
							tableName: data[a].tableName
						})
					}
					sqlTableJSON[data[a].tableName] = true;

				}

				sort.sortListBySn(sqlFieldList);
				$scope.data.fieldsList = sqlFieldList;
				$scope.search.canSelectList = $.extend(true, [], sqlFieldList);
				$scope.sqlTableList = sqlTableList;

				$scope.data.sqlTableList = JSON.stringify(sqlTableList);
				// 设置表名和主键
				$scope.data.tableName = $scope.data.tableName || sqlTableList[0].tableName;
				$scope.data.pkName = $scope.data.pkName || sqlFieldList[0].fieldName;
				$scope.data.name = $scope.data.name || $scope.data.tableName.tuoFeng();
				$scope.data.code = $scope.data.code || $scope.data.tableName.tuoFeng();

			} else {
				$.Dialog.error(data.msg, data.cause);
			}
		});

	}

	// 自动给sql添加别名
	$scope.addAliases = function () {

		if (!$scope.data.sqlContent) {
			$.Dialog.error("请输入sql查询脚本");
			return;
		}
		baseService.post(__ctx + '/form/formCustSql/addAliases', {
			sqlContent: $scope.data.sqlContent
		}).then(function (data) {

			if (!data.isOk) {
				$.Dialog.error(data.msg);
				return;
			}
			$scope.data.sqlContent = $scope.formatSql(data.data);
		});
	};

	// 保存自定义列表
	$scope.saveData = function (isPreview) {

		// 校验参数
		if ($("#formCustSqlForm").find(".ng-invalid")[0]) {
			$.Dialog.error("表单填写不正确");
			return;
		}

		var data = angular.copy($scope.data);
		// 设置查询列表
		data.conditions = "";
		if ($scope.search.selectSearchList) {
			for (var i = 0; i < $scope.search.selectSearchList.length; i++) {
				$scope.search.selectSearchList.sn = i + 1;
			}
			data.conditions = JSON.stringify($scope.search.selectSearchList);
		}

		// 设置按钮
		if ($scope.button.buttonList) {
			$scope.handleButtonList();
			data.buttons = JSON.stringify($scope.button.buttonList);
		}
		data.expand = JSON.stringify(data.expand);

		// 保存数据
		baseService.post(__ctx + '/form/formCustSql/save', data).then(function (data) {
			console.log("说句吗啊啊啊啊", data)
			if (data.isOk) {
				window.reloadGrid && window.reloadGrid();
				parent.reloadGrid && parent.reloadGrid();
				$scope.data.id = data.data;
				if (isPreview) {
					var url = "form/formCustSql/view/formCustSqlView.html?code=" + $scope.data.code;
					// 改成都用新窗口打开,否则有时在编辑的时候,需要关掉编辑框才能预览
					window.open("view/formCustSqlView.html?code=" + $scope.data.code);
					//				    if ( top && top.addTab ) {
					//					    top.addTab ( {
					//					        id : $scope.data.code ,
					//					        name : $scope.data.name ,
					//					        icon : "fa-list" ,
					//					        url : url ,
					//					        closable : true
					//					    } );
					//				    } else {
					//					    window.open ( "view/formCustSqlView.html?code=" + $scope.data.code );
					//				    }
				} else {
					$.Dialog.success("保存成功");
				}

				//				不需要刷新和关闭,方便修改
				//				jQuery.Dialog.confirm ( "操作成功" , data.data + ",是否继续操作" , function ( ) {
				//				} , function ( ) {
				//					$.Dialog.close ( window );
				//					window.location.reload ( );
				//				} );
			} else {
				$.Dialog.error(data.msg, data.cause);
			}
		});
	}


	$scope.openSetting = {
		open: function (data, key, openTypeMap) {
			data = data || {};
			$scope.openSetting.openTypeMap = openTypeMap;
			$scope.openSetting.data = $.extend(true, {
				openType: "3",
				width: "1200",
				height: "800",
				widthUnit: "px",
				heightUnit: "px",
			}, data[key]);
			$scope.openSetting.sourceObj = data;
			$scope.openSetting.sourceKey = key;
			$("#openSettingModal").modal("show");
		},
		data: {},
		saveData: function () {
			$scope.openSetting.sourceObj[$scope.openSetting.sourceKey] = $.extend(true, {}, $scope.openSetting.data);
			$("#openSettingModal").modal("hide");
		}
	};

	$scope.init();

}]).service('formCustSqlService', ['baseService', function (baseService) {

	var pages = [5, 10, 20, 50, 100, 200, 500];
	var pageSizeArray = [];
	for (var i = 0; i < pages.length; i++) {
		pageSizeArray.push({
			label: pages[i] + "",
			value: pages[i] + "",
		});
	}
	;
	var service = {
		pageSizeArray: pageSizeArray,
		statusJson: {
			"0": "否",
			"1": "是"
		},
		dateTypeMap: {
			"yyyy": "yyyy",
			"yyyy-MM": "yyyy-MM",
			"yyyy-MM-dd": "yyyy-MM-dd",
			"yyyy-MM-dd hh:mm": "yyyy-MM-dd hh:mm",
			"yyyy-MM-dd hh:mm:ss": "yyyy-MM-dd hh:mm:ss",
			"hh:mm:ss": "yyyy-MM-dd",
		},
		alignMap: {
			l: "left",
			c: "center",
			r: "right"
		},
		// 条件类型
		cnTypeMap: {
			"=": "等于",
			"<": "小于",
			">": "大于",
			">=": "大于等于",
			"<=": "小于等于",
			"<>": "不等于",
			"like": "like",
			"llike": "左like",
			"rlike": "右like",
			"in": "in",
			"not in": "not in",
			"is null": "空", // 这里不能用null 否则会报错
			"not null": "非空",
			">=,<=": "范围【全包括】",
			">,<": "范围【不包括】",
			">=,<": "范围【左包括】",
			">,<=": "范围【右包括】"
		},
		// 控件类型
		controlTypeMap: {
			"1": "单行文本框",
			"2": "多行文本",
			"3": "日期控件",
			"4": "下拉框",
			"5": "数据字典",
			"6": "单选框",
			"7": "[字典]单选框",
			"8": "复选框",
			"9": "[字典]复选框",
			"10": "json",
		},
		// 自动赋值的变量类型
		initTypeMap: {
			"1": "固定值",
			"2": "当前日期",
			"3": "当前用户Id",
			"4": "当前用户名",
			"7": "当前组织ID",
			"8": "当前组织名称",
		},
		colMutiMap: {
			2: '两倍',
			3: '三倍',
			4: '四倍'
		},
		paramTypeMap: {
			1: '普通',
			2: 'freemarker变量'
		},
		selectTypeMap: {
			"1": "单选",
			"2": "多选",
		},
		// 按钮类型
		btnTypes: {
			"1": "行内按钮",
			"2": "全局按钮",
		},
		// 按钮点击类型
		btnClickTypes: {
			"0": "直接请求",
			"1": "事件按钮",
			"2": "标签页/tab页",
			"3": "普通对话框",
			"4": "TOP对话框",
			"5": "新页面",
		},
		// 按钮点击类型
		btnStyleTypes: {
			"btn-primary": "btn-primary",
			"btn-success": "btn-success",
			"btn-info": "btn-info",
			"btn-warning": "btn-warning",
			"btn-default": "btn-default",
			"btn-danger": "btn-danger"
		},
		// 列表href打开类型
		hrefOpenTypes: {
			"2": "标签页/tab页",
			"3": "普通对话框",
			"4": "TOP对话框",
			"5": "新页面",
		},
		showTypeMap: {
			"1": "显示",
			"2": "隐藏",
			"3": "禁用",
			"4": "移除"
		},
		unitTypeMap: {
			"px": "px",
			"%": "%",
		},
	}
	return service;

}])
	// 基础设置
	.directive('customSqlBaseSetting', function ($compile, $timeout, $injector, baseService) {

		return {
			restrict: 'E',
			templateUrl: "../../form/formCustSql/setting/baseSetting.html",
			replace: true,
			link: function (scope, elm, attrs) {

				scope.thisScope = scope;
			}
		};
	})
	// 字段设置
	.directive('customSqlFieldsSetting', function ($compile, $timeout, $injector, baseService) {

		return {
			restrict: 'E',
			templateUrl: "../../form/formCustSql/setting/fieldsSetting.html",
			replace: true,
			link: function (scope, elm, attrs) {

				scope.thisScope = scope;
			}
		};
	})
	// 查询设置
	.directive('customSqlSearchSetting', function ($compile, $timeout, $injector, baseService) {

		return {
			restrict: 'E',
			templateUrl: "../../form/formCustSql/setting/searchSetting.html",
			replace: true,
			link: function (scope, elm, attrs) {

				scope.thisScope = scope;
				scope.search = scope.search || {};
				var $scope = scope;

				// 选择可查询列表字段的方法
				$scope.search.selectSerchField = function (item) {

					$scope.search.selectSearchList = $scope.search.selectSearchList || [];
					item = angular.copy(item);
					item.sn = $scope.search.selectSearchList.length + 1;
					switch (item.controlType) {
						case "1":
						case 1:
							item.cntype = "like";
							break;
						default:
							item.cntype = "=";
							break;
					}
					item.init = "0";
					item.paramType = "1";// 普通变量
					$scope.search.selectSearchList.push({
						tableName: item.tableName,
						tableAlias: item.tableAlias,
						name: item.fieldName,
						desc: item.fieldDesc,
						cntype: item.cntype,
						ctltype: item.controlType,
						json: item.dateFormat,
						init: item.init,
						dfDataType: item.initType,
						val: item.val,
						sn: item.sn,
						showType: 1,
						isMust: 0,
						colMuti: item.colMuti,
						type: item.dataType,
						paramType: item.paramType,
					});
				};
			}
		};
	})
	// 按钮设置
	.directive('customSqlButtonSetting', function ($compile, $timeout, $injector, baseService) {

		return {
			restrict: 'E',
			templateUrl: "../../form/formCustSql/setting/buttonSetting.html",
			replace: true,
			link: function (scope, elm, attrs) {

				scope.thisScope = scope;
				scope.button = scope.button || {};
				var $scope = scope;

				scope.button.addButton = function () {

					scope.button.buttonList = scope.button.buttonList || [];
					scope.button.buttonList.push({
						name: "按钮",
						alias: "btn",
						type: "1",// 行内按钮
						clickType: "1",// 直接请求
						icon: "fa-delicious",
						btncss: "btn-primary",
						warnTxt: "",
						mustSelect: 1,
						dataChange: "",
						url: "",
						exp: "true",
					});
				}

				$scope.button.quickData = {
					name: "开启",
					status: "status",
					staValue: "1"
				}

				$scope.button.custFormBtn = function (type) {
					if (!$scope.data.custForm || !$scope.data.custForm.formKey) {
						$.Dialog.warning("配置该按钮需要首先绑定在线表单！");
						return;
					}
					var formKey = $scope.data.custForm.formKey;
					var btn;
					if (type == 'add') btn = {
						name: "新增", alias: "xx:add", type: "2", clickType: "3", exp: "true",
						icon: "fa-plus", btncss: "btn-primary", warnTxt: "",
						url: "/form/formDef/vueFormDefPreview.html?sql=1&key=" + formKey
					};
					// if(type=='setup') btn = { name : "参数设置" ,  alias : "xx:setup" , type : "2" , clickType : "3" ,  exp : "true",
					// 	icon : "fa-plus" , btncss : "btn-primary" ,  warnTxt : "" ,
					// 	url : "/form/formDef/vueFormDefPreview.html?sql=1&key="+formKey
					// };
					if (type == 'del') btn = {
						name: "删除", alias: "xx:del", type: "1", clickType: "0", exp: "true",
						icon: "fa-trash", btncss: "btn-primary", warnTxt: "确认删除", mustSelect: 1,
						url: "/form/formDefData/removeData/" + formKey + "/${" + $scope.data.pkName + "}"
					};
					if (type == 'edit') btn = {
						name: "编辑", alias: "xx:edit", type: "1", clickType: "3", exp: "true",
						icon: "fa-edit", btncss: "btn-primary", warnTxt: "", mustSelect: 1,
						url: "/form/formDef/vueFormDefPreview.html?sql=1&key=" + formKey + "&id=${" + $scope.data.pkName + "}"
					};

					if (type == 'detail') btn = {
						name: "详情", alias: "xx:detail", type: "1", clickType: "3", exp: "true",
						icon: "fa-detail", btncss: "btn-primary", warnTxt: "", mustSelect: 1,
						url: "/form/formDef/vueFormDetail.html?key=" + formKey + "&id=${" + $scope.data.pkName + "}"
					};

					if (!$scope.button.buttonList) {
						$scope.button.buttonList = [];
					}

					if (btn) $scope.button.buttonList.push(JsonUtil.ps(btn));
				}

				$scope.button.quickSaveButton = function (name, status, staValue, isClose) {

					if (!name) {
						$.Dialog.alert("请输入名称!");
						return;
					}
					if (!status) {
						$.Dialog.alert("请输入状态字段!");
						return;
					}
					if (!staValue) {
						$.Dialog.alert("请输入状态值!");
						return;
					}

					var btn = '{"type": "1",clickType:"1", "exp": "item.status!=staValue", "btncss": "btn-primary", "icon": "fa-send", "name": "开启","mustSelect" : 1, "alias": "open", "warnTxt": "是否开启", "dataChange": "status=staValue"}';
					btn = btn.replaceAll("开启", name);
					if (!isClose) {
						btn = btn.replaceAll("open", status + "Open");
					} else {
						btn = btn.replaceAll("open", status + "Close");
					}
					btn = btn.replaceAll("status", status);
					btn = btn.replaceAll("staValue", staValue);
					if (isClose) {
						btn = btn.replaceAll("fa-send", "fa-power-off");
					}
					btn = btn.replaceAll("primary", GetRandomList(["primary", "warning", "info", "success", "danger", "default"]));

					$scope.button.buttonList = $scope.button.buttonList || [];

					$scope.button.buttonList.push(JsonUtil.ps(btn));

				};

				$scope.button.genBtnJson = function (item) {

					$scope.button.btnJson = JSON.stringify(item);
				}

				$scope.button.quickSaveBtn = function (btnJson) {

					if (!btnJson) {
						$.Dialog.alert("请先输入数据");
						return;
					} else {
						btnJson = JsonUtil.ps(btnJson);
					}
					if (!btnJson) {
						$.Dialog.alert("数据格式错误");
						return;
					}
					$scope.button.buttonList = $scope.button.buttonList || [];
					$scope.button.buttonList.push(btnJson);
				}
			}
		};
	}).service('customSqlFieldsSettingService', ['baseService', function (baseService) {

		var service = {};
		return service;
	}])
